<?php
/**
 * Payment page controller
 *
 * @author dima
 *
 */

class PaymentController extends modules_default_controllers_ControllerBase
{
	
//----------------------------------------------------------------------------------------------------
	
	protected $_bForLoggedUsersOnly = false;
	
//----------------------------------------------------------------------------------------------------

	public $ajaxable = array(
		'delete' => array('json'),
		'update' => array('json'),
		'deletebanner' => array('json'),
	);	
			
//----------------------------------------------------------------------------------------------------
	
	public function init()
	{
		if (! $this->getRequest()->isXmlHttpRequest())
		{
			parent::init();
			$this->view->title = 'Payment';
		}
		
		$this->_helper->AjaxContext()->initContext('json');
	}
	
//----------------------------------------------------------------------------------------------------
	
	public function indexAction()
	{
		$oRequest = $this->getRequest();
		$idItem = $oRequest->getParam('id');
		
		$aIdentity = Zend_Auth::getInstance()->getIdentity();
		$idUser = $aIdentity['User_id'];		
		if (!$idUser)
		{
			$this->_redirect('/');			
		}
		else
		{
			$aItem 	= models_ContentitemsMapper::findByContributor($idUser, 'awaiting_payment');
			
			$this->view->aItem = $aItem;

			$aItemPayed 	= models_OrdersMapper::findAll(1, 'payed', $idUser);
			$this->view->aItemPayed = $aItemPayed;
			
			$this->view->ourEmail	= models_Orders::OUR_EMAIL;
			$this->view->categoryName = 'My orders';
		}
	}

//----------------------------------------------------------------------------------------------------
	
//----------------------------------------------------------------------------------------------------
	
	public function ipnhandlerAction()
	{
		define('PAYPAL_SERVER', 'sandbox');
		models_PaymentMapper::writeLogAction("****************************************************************************************************\n");

//		$rrr = print_r($_POST, true);
//		models_PaymentMapper::writeLogAction("\n***\n" . $rrr . "\n***\n");
	
		if (array_key_exists("txn_id", $_POST))
		{
			$logStr = "Received IPN,  TX ID : " . htmlspecialchars($_POST["txn_id"]);
			models_PaymentMapper::writeLogAction($logStr);
			
		}
		else
		{
			$logStr = "IPN Listner recieved an HTTP request with out a Transaction ID.";
			models_PaymentMapper::writeLogAction($logStr);
			exit();
		}

		$tmpAr = array_merge($_POST, array ("cmd" => "_notify-validate"));
		$postFieldsAr = array ();
		foreach ($tmpAr as $name => $value)
		{
			$postFieldsAr[] = "$name=$value";
		}

		$logStr = "Sending IPN values:\n" . implode("\n", $postFieldsAr);
		models_PaymentMapper::writeLogAction($logStr);
		

		$ppResponseAr = self::PPHttpPost("https://" . PAYPAL_SERVER . ".paypal.com/cgi-bin/webscr", implode("&", $postFieldsAr), false);
//		models_PaymentMapper::writeLogAction("\n***\nrespon\n***\n" . $ppResponseAr . "\n***\n");
		
		$logStr = "Received response: " . var_export($ppResponseAr, 1);
		models_PaymentMapper::writeLogAction($logStr);


		if (! $ppResponseAr["status"])
		{
			$logStr = "--------------------\n" . "IPN Listner recieved an Error:\n";
			
			models_PaymentMapper::writeLogAction($logStr);
			
			if (0 !== $ppResponseAr["error_no"])
			{
				$logStr .= "Error " . $ppResponseAr["error_no"] . ": ";
			}
			$logStr .= $ppResponseAr["error_msg"];
			models_PaymentMapper::writeLogAction($logStr);
			exit();
		}

		$logStr = 	   "--------------------\nIPN Post Response:\n" . $ppResponseAr["httpResponse"];
		models_PaymentMapper::writeLogAction($logStr);


		if ($ppResponseAr["httpResponse"] == 'VERIFIED')
		{
			$item_id = $_POST['item_number'];
			
			
			$data 	= array('status' => 'payed',
							'processed'	=> Lemar_Date::getCurrentDate(Lemar_Date::MYSQL_DATETIME));
			$ret2 = models_CreditMapper::edit($item_id, $data);
			
			$logStr = "Setting active item #:" . $item_id . "\r\n";
			models_PaymentMapper::writeLogAction($logStr);
				
		
		// put here the function which makes content item active and order status payed
		}
	}
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------

/**
 * Builds the URL for the input file using the HTTP request information
 *
 * @param	string	The name of the new file
 * @return	string	The full URL for the input file
 *
 * @access	public
 * @static
 */
function getURL ($fileContextPath_)
{

	$server_protocol = htmlspecialchars($_SERVER["SERVER_PROTOCOL"]);
	$server_name = htmlspecialchars($_SERVER["SERVER_NAME"]);
	$server_port = htmlspecialchars($_SERVER["SERVER_PORT"]);
	$url = strtolower(substr($server_protocol, 0, strpos($server_protocol, '/'))); // http
	$url .= "://$server_name:$server_port/$fileContextPath_";
	
	return $url;
} // getURL
	
//----------------------------------------------------------------------------------------------------


/**
 * Send HTTP POST Request
 *
 * @param	string	The request URL
 * @param	string	The POST Message fields in &name=value pair format
 * @param	bool		determines whether to return a parsed array (true) or a raw array (false)
 * @return	array		Contains a bool status, error_msg, error_no,
 *				and the HTTP Response body(parsed=httpParsedResponseAr  or non-parsed=httpResponse) if successful
 *
 * @access	public
 * @static
 */
function PPHttpPost ($url_, $postFields_, $parsed_)
{

	//setting the curl parameters.
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url_);
	curl_setopt($ch, CURLOPT_VERBOSE, 1);
	
	//turning off the server and peer verification(TrustManager Concept).
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POST, 1);
	
	//setting the nvpreq as POST FIELD to curl
	curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields_);
	
	//getting response from server
	$httpResponse = curl_exec($ch);
	//return $httpResponse;die;
	if (! $httpResponse)
	{
		return array (
			"status" => false , "error_msg" => curl_error($ch) , "error_no" => curl_errno($ch));
	}
	
	if (! $parsed_)
	{
		return array (
			"status" => true , "httpResponse" => $httpResponse);
	}
	
	$httpResponseAr = explode("\n", $httpResponse);
	
	$httpParsedResponseAr = array ();
	foreach ($httpResponseAr as $i => $value)
	{
		$tmpAr = explode("=", $value);
		if (sizeof($tmpAr) > 1)
		{
			$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
		}
	}
	
	if (0 == sizeof($httpParsedResponseAr))
	{
		$error = "Invalid HTTP Response for POST request($postFields_) to $url_.";
		return array (
			"status" => false , "error_msg" => $error , "error_no" => 0);
	}
	return array (
		"status" => true , "httpParsedResponseAr" => $httpParsedResponseAr);

} // PPHttpPost	
	
//----------------------------------------------------------------------------------------------------

/**
 * Redirect to Error Page
 *
 * @param	string	Error message
 * @param	int		Error number
 *
 * @access	public
 * @static
 */
function PPError ($error_msg, $error_no)
{

	// create a new curl resource
	$ch = curl_init();
	
	// set URL and other appropriate options
	$php_self = substr(htmlspecialchars($_SERVER["PHP_SELF"]), 1); // remove the leading /
	$redirectURL = getURL(substr_replace($php_self, "Error.php", strrpos($php_self, '/') + 1));
	curl_setopt($ch, CURLOPT_URL, $redirectURL);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
	
	// set POST fields
	$postFields = "error_msg=" . urlencode($error_msg) . "&error_no=" . urlencode($error_no);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
	
	// grab URL, and print
	curl_exec($ch);
	curl_close($ch);
}

//----------------------------------------------------------------------------------------------------

	
}
